package info.zlong.visibleruntime.logback;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.AppenderBase;
import info.zlong.visibleruntime.core.model.LogMsg;
import info.zlong.visibleruntime.core.mongo.MongoConnector;

public class MongoDBAppender extends AppenderBase<LoggingEvent> {
	private static Logger logger = LoggerFactory.getLogger(MongoDBAppender.class);

	private String hosts;
	private String userName;
	private String password;
	private String databaseName;
	private String collectionName;
	private MongoConnector mongoConnector;
	   

    @Override
    public void start() {
		mongoConnector = new MongoConnector(hosts,userName,password, databaseName, collectionName);
    	mongoConnector.open();
        super.start();
    }
    


    @Override
    public void stop() {
    	mongoConnector.close();
        super.stop();
    }

    @Override
    protected void append(LoggingEvent event) {
		String msg = event.getFormattedMessage();try{
			LogMsg logMsg = JSON.parseObject(msg, LogMsg.class);
			mongoConnector.update(logMsg);
			}catch (Exception e) {
				logger.error("LogMsg存入Mongo出错:"+msg,e);
			}
    }

	public void setHosts(String hosts) {
		this.hosts = hosts;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setDatabaseName(String databaseName) {
		this.databaseName = databaseName;
	}

	public void setCollectionName(String collectionName) {
		this.collectionName = collectionName;
	}
}
